from flask import Blueprint, request, jsonify
from models import db
from sqlalchemy.exc import IntegrityError
from sqlalchemy import text

from models.models import User
from models.users import Role, Resource, Permission

# 创建蓝图
views_bp = Blueprint('views', __name__)

# ==================== 用户管理 ====================

@views_bp.route('/users', methods=['GET'])
def get_users():
    """获取所有用户"""
    try:
        # 使用原生SQL查询
        result = db.session.execute(text("""
            SELECT u.id, u.name, u.mobile, u.roleid, u.created_at, r.name as role_name
            FROM admin_user u
            LEFT JOIN roles r ON u.roleid = r.id
            ORDER BY u.id
        """)).fetchall()
        
        users_list = []
        for row in result:
            users_list.append({
                'id': row[0],
                'name': row[1],
                'mobile': row[2],
                'role_id': row[3],
                'role_name': row[5],
                'created_at': row[4].strftime('%Y-%m-%d %H:%M:%S') if row[4] else None
            })
        
        return jsonify({'code': 200, 'message': '获取成功', 'data': users_list})
    except Exception as e:
        return jsonify({'code': 500, 'message': f'获取失败: {str(e)}'}), 500

@views_bp.route('/users', methods=['POST'])
def create_user():
    """创建用户"""
    try:
        data = request.get_json()
        username = data.get('username')
        email = data.get('email')
        role_id = data.get('role_id')
        
        if not username or not email:
            return jsonify({'code': 400, 'message': '用户名和邮箱不能为空'}), 400
        
        # 检查用户名是否已存在
        if User.query.filter_by(username=username).first():
            return jsonify({'code': 400, 'message': '用户名已存在'}), 400
        
        # 检查邮箱是否已存在
        if User.query.filter_by(email=email).first():
            return jsonify({'code': 400, 'message': '邮箱已存在'}), 400
        
        # 创建用户
        user = User(username=username, email=email, role_id=role_id)
        db.session.add(user)
        db.session.commit()
        
        return jsonify({
            'code': 200, 
            'message': '创建成功', 
            'data': {
                'id': user.id,
                'username': user.username,
                'email': user.email,
                'role_id': user.role_id
            }
        })
    except IntegrityError:
        db.session.rollback()
        return jsonify({'code': 400, 'message': '数据完整性错误'}), 400
    except Exception as e:
        db.session.rollback()
        return jsonify({'code': 500, 'message': f'创建失败: {str(e)}'}), 500

@views_bp.route('/users/<int:user_id>', methods=['GET'])
def get_user(user_id):
    """获取单个用户"""
    try:
        user = User.query.get(user_id)
        if not user:
            return jsonify({'code': 404, 'message': '用户不存在'}), 404
        
        return jsonify({
            'code': 200,
            'message': '获取成功',
            'data': {
                'id': user.id,
                'username': user.username,
                'email': user.email,
                'role_id': user.role_id,
                'create_time': user.create_time.strftime('%Y-%m-%d %H:%M:%S') if user.create_time else None
            }
        })
    except Exception as e:
        return jsonify({'code': 500, 'message': f'获取失败: {str(e)}'}), 500

@views_bp.route('/users/<int:user_id>', methods=['PUT'])
def update_user(user_id):
    """更新用户"""
    try:
        user = User.query.get(user_id)
        if not user:
            return jsonify({'code': 404, 'message': '用户不存在'}), 404
        
        data = request.get_json()
        username = data.get('username')
        email = data.get('email')
        role_id = data.get('role_id')
        
        # 更新字段
        if username:
            # 检查用户名是否被其他用户使用
            existing_user = User.query.filter_by(username=username).first()
            if existing_user and existing_user.id != user_id:
                return jsonify({'code': 400, 'message': '用户名已被使用'}), 400
            user.username = username
        
        if email:
            # 检查邮箱是否被其他用户使用
            existing_user = User.query.filter_by(email=email).first()
            if existing_user and existing_user.id != user_id:
                return jsonify({'code': 400, 'message': '邮箱已被使用'}), 400
            user.email = email
        
        if role_id is not None:
            user.role_id = role_id
        
        db.session.commit()
        
        return jsonify({
            'code': 200,
            'message': '更新成功',
            'data': {
                'id': user.id,
                'username': user.username,
                'email': user.email,
                'role_id': user.role_id
            }
        })
    except IntegrityError:
        db.session.rollback()
        return jsonify({'code': 400, 'message': '数据完整性错误'}), 400
    except Exception as e:
        db.session.rollback()
        return jsonify({'code': 500, 'message': f'更新失败: {str(e)}'}), 500

@views_bp.route('/users/<int:user_id>', methods=['DELETE'])
def delete_user(user_id):
    """删除用户"""
    try:
        user = User.query.get(user_id)
        if not user:
            return jsonify({'code': 404, 'message': '用户不存在'}), 404
        
        db.session.delete(user)
        db.session.commit()
        
        return jsonify({'code': 200, 'message': '删除成功'})
    except Exception as e:
        db.session.rollback()
        return jsonify({'code': 500, 'message': f'删除失败: {str(e)}'}), 500

# ==================== 角色管理 ====================

@views_bp.route('/roles', methods=['GET'])
def get_roles():
    """获取所有角色"""
    try:
        # 使用原生SQL查询
        result = db.session.execute(text("""
            SELECT id, name, description, created_at 
            FROM roles 
            ORDER BY id
        """)).fetchall()
        
        roles_list = []
        for row in result:
            roles_list.append({
                'id': row[0],
                'name': row[1],
                'description': row[2],
                'created_at': row[3].strftime('%Y-%m-%d %H:%M:%S') if row[3] else None
            })
        
        return jsonify({'code': 200, 'message': '获取成功', 'data': roles_list})
    except Exception as e:
        return jsonify({'code': 500, 'message': f'获取失败: {str(e)}'}), 500

@views_bp.route('/roles', methods=['POST'])
def create_role():
    """创建角色"""
    try:
        data = request.get_json()
        name = data.get('name')
        description = data.get('description', '')
        
        if not name:
            return jsonify({'code': 400, 'message': '角色名称不能为空'}), 400
        
        # 检查角色名是否已存在
        existing_role = db.session.execute(text("SELECT id FROM roles WHERE name = :name"), {'name': name}).fetchone()
        if existing_role:
            return jsonify({'code': 400, 'message': '角色名已存在'}), 400
        
        # 获取下一个可用的ID
        max_id_result = db.session.execute(text("SELECT MAX(id) FROM roles")).fetchone()
        next_id = (max_id_result[0] or 0) + 1
        
        # 创建角色
        db.session.execute(text("""
            INSERT INTO roles (id, name, description, created_at) 
            VALUES (:id, :name, :description, NOW())
        """), {'id': next_id, 'name': name, 'description': description})
        db.session.commit()
        
        # 获取新创建的角色ID
        new_role = db.session.execute(text("SELECT id FROM roles WHERE name = :name"), {'name': name}).fetchone()
        
        return jsonify({
            'code': 200,
            'message': '创建成功',
            'data': {
                'id': new_role[0],
                'name': name,
                'description': description
            }
        })
    except IntegrityError:
        db.session.rollback()
        return jsonify({'code': 400, 'message': '数据完整性错误'}), 400
    except Exception as e:
        db.session.rollback()
        return jsonify({'code': 500, 'message': f'创建失败: {str(e)}'}), 500

@views_bp.route('/roles/<int:role_id>', methods=['GET'])
def get_role(role_id):
    """获取单个角色"""
    try:
        role = Role.query.get(role_id)
        if not role:
            return jsonify({'code': 404, 'message': '角色不存在'}), 404
        
        return jsonify({
            'code': 200,
            'message': '获取成功',
            'data': {
                'id': role.id,
                'name': role.name,
                'description': role.description,
                'created_at': role.created_at.strftime('%Y-%m-%d %H:%M:%S') if role.created_at else None
            }
        })
    except Exception as e:
        return jsonify({'code': 500, 'message': f'获取失败: {str(e)}'}), 500

@views_bp.route('/roles/<int:role_id>', methods=['PUT'])
def update_role(role_id):
    """更新角色"""
    try:
        role = Role.query.get(role_id)
        if not role:
            return jsonify({'code': 404, 'message': '角色不存在'}), 404
        
        data = request.get_json()
        name = data.get('name')
        description = data.get('description')
        
        # 更新字段
        if name:
            # 检查角色名是否被其他角色使用
            existing_role = Role.query.filter_by(name=name).first()
            if existing_role and existing_role.id != role_id:
                return jsonify({'code': 400, 'message': '角色名已被使用'}), 400
            role.name = name
        
        if description is not None:
            role.description = description
        
        db.session.commit()
        
        return jsonify({
            'code': 200,
            'message': '更新成功',
            'data': {
                'id': role.id,
                'name': role.name,
                'description': role.description
            }
        })
    except IntegrityError:
        db.session.rollback()
        return jsonify({'code': 400, 'message': '数据完整性错误'}), 400
    except Exception as e:
        db.session.rollback()
        return jsonify({'code': 500, 'message': f'更新失败: {str(e)}'}), 500

@views_bp.route('/roles/<int:role_id>', methods=['DELETE'])
def delete_role(role_id):
    """删除角色"""
    try:
        role = Role.query.get(role_id)
        if not role:
            return jsonify({'code': 404, 'message': '角色不存在'}), 404
        
        db.session.delete(role)
        db.session.commit()
        
        return jsonify({'code': 200, 'message': '删除成功'})
    except Exception as e:
        db.session.rollback()
        return jsonify({'code': 500, 'message': f'删除失败: {str(e)}'}), 500

# ==================== 资源管理 ====================

@views_bp.route('/resources', methods=['GET'])
def get_resources():
    """获取所有资源"""
    try:
        resources = Resource.query.all()
        result = []
        for resource in resources:
            result.append({
                'id': resource.id,
                'name': resource.name,
                'pid': resource.pid,
                'level': resource.level,
                'topid': resource.topid,
                'url': resource.url,
                'icon': resource.icon,
                'sort': resource.sort,
                'status': resource.status
            })
        return jsonify({'code': 200, 'message': '获取成功', 'data': result})
    except Exception as e:
        return jsonify({'code': 500, 'message': f'获取失败: {str(e)}'}), 500

@views_bp.route('/resources', methods=['POST'])
def create_resource():
    """创建资源"""
    try:
        data = request.get_json()
        name = data.get('name')
        pid = data.get('pid', 0)
        level = data.get('level', 1)
        topid = data.get('topid', 0)
        url = data.get('url', '')
        icon = data.get('icon', '')
        sort = data.get('sort', 0)
        status = data.get('status', True)
        
        if not name:
            return jsonify({'code': 400, 'message': '资源名称不能为空'}), 400
        
        # 创建资源
        resource = Resource(
            name=name, pid=pid, level=level, topid=topid,
            url=url, icon=icon, sort=sort, status=status
        )
        db.session.add(resource)
        db.session.commit()
        
        return jsonify({
            'code': 200,
            'message': '创建成功',
            'data': {
                'id': resource.id,
                'name': resource.name,
                'pid': resource.pid,
                'level': resource.level,
                'topid': resource.topid,
                'url': resource.url,
                'icon': resource.icon
            }
        })
    except Exception as e:
        db.session.rollback()
        return jsonify({'code': 500, 'message': f'创建失败: {str(e)}'}), 500

@views_bp.route('/resources/<int:resource_id>', methods=['GET'])
def get_resource(resource_id):
    """获取单个资源"""
    try:
        resource = Resource.query.get(resource_id)
        if not resource:
            return jsonify({'code': 404, 'message': '资源不存在'}), 404
        
        return jsonify({
            'code': 200,
            'message': '获取成功',
            'data': {
                'id': resource.id,
                'name': resource.name,
                'pid': resource.pid,
                'level': resource.level,
                'topid': resource.topid,
                'url': resource.url,
                'icon': resource.icon,
                'sort': resource.sort,
                'status': resource.status
            }
        })
    except Exception as e:
        return jsonify({'code': 500, 'message': f'获取失败: {str(e)}'}), 500

@views_bp.route('/resources/<int:resource_id>', methods=['PUT'])
def update_resource(resource_id):
    """更新资源"""
    try:
        resource = Resource.query.get(resource_id)
        if not resource:
            return jsonify({'code': 404, 'message': '资源不存在'}), 404
        
        data = request.get_json()
        
        # 更新字段
        if 'name' in data:
            resource.name = data['name']
        if 'pid' in data:
            resource.pid = data['pid']
        if 'level' in data:
            resource.level = data['level']
        if 'topid' in data:
            resource.topid = data['topid']
        if 'url' in data:
            resource.url = data['url']
        if 'icon' in data:
            resource.icon = data['icon']
        if 'sort' in data:
            resource.sort = data['sort']
        if 'status' in data:
            resource.status = data['status']
        
        db.session.commit()
        
        return jsonify({
            'code': 200,
            'message': '更新成功',
            'data': {
                'id': resource.id,
                'name': resource.name,
                'pid': resource.pid,
                'level': resource.level,
                'topid': resource.topid,
                'url': resource.url,
                'icon': resource.icon
            }
        })
    except Exception as e:
        db.session.rollback()
        return jsonify({'code': 500, 'message': f'更新失败: {str(e)}'}), 500

@views_bp.route('/resources/<int:resource_id>', methods=['DELETE'])
def delete_resource(resource_id):
    """删除资源"""
    try:
        resource = Resource.query.get(resource_id)
        if not resource:
            return jsonify({'code': 404, 'message': '资源不存在'}), 404
        
        db.session.delete(resource)
        db.session.commit()
        
        return jsonify({'code': 200, 'message': '删除成功'})
    except Exception as e:
        db.session.rollback()
        return jsonify({'code': 500, 'message': f'删除失败: {str(e)}'}), 500

# ==================== 权限管理 ====================

@views_bp.route('/permissions', methods=['GET'])
def get_permissions():
    """获取所有权限"""
    try:
        permissions = Permission.query.all()
        result = []
        for permission in permissions:
            result.append({
                'id': permission.id,
                'name': permission.name,
                'resource_id': permission.resource_id,
                'action': permission.action,
                'created_at': permission.created_at.strftime('%Y-%m-%d %H:%M:%S') if permission.created_at else None
            })
        return jsonify({'code': 200, 'message': '获取成功', 'data': result})
    except Exception as e:
        return jsonify({'code': 500, 'message': f'获取失败: {str(e)}'}), 500

@views_bp.route('/permissions', methods=['POST'])
def create_permission():
    """创建权限"""
    try:
        data = request.get_json()
        name = data.get('name')
        resource_id = data.get('resource_id')
        action = data.get('action')
        
        if not name or not resource_id or not action:
            return jsonify({'code': 400, 'message': '权限名称、资源ID和操作类型不能为空'}), 400
        
        # 创建权限
        permission = Permission(name=name, resource_id=resource_id, action=action)
        db.session.add(permission)
        db.session.commit()
        
        return jsonify({
            'code': 200,
            'message': '创建成功',
            'data': {
                'id': permission.id,
                'name': permission.name,
                'resource_id': permission.resource_id,
                'action': permission.action
            }
        })
    except Exception as e:
        db.session.rollback()
        return jsonify({'code': 500, 'message': f'创建失败: {str(e)}'}), 500

@views_bp.route('/permissions/<int:permission_id>', methods=['GET'])
def get_permission(permission_id):
    """获取单个权限"""
    try:
        permission = Permission.query.get(permission_id)
        if not permission:
            return jsonify({'code': 404, 'message': '权限不存在'}), 404
        
        return jsonify({
            'code': 200,
            'message': '获取成功',
            'data': {
                'id': permission.id,
                'name': permission.name,
                'resource_id': permission.resource_id,
                'action': permission.action,
                'created_at': permission.created_at.strftime('%Y-%m-%d %H:%M:%S') if permission.created_at else None
            }
        })
    except Exception as e:
        return jsonify({'code': 500, 'message': f'获取失败: {str(e)}'}), 500

@views_bp.route('/permissions/<int:permission_id>', methods=['PUT'])
def update_permission(permission_id):
    """更新权限"""
    try:
        permission = Permission.query.get(permission_id)
        if not permission:
            return jsonify({'code': 404, 'message': '权限不存在'}), 404
        
        data = request.get_json()
        
        # 更新字段
        if 'name' in data:
            permission.name = data['name']
        if 'resource_id' in data:
            permission.resource_id = data['resource_id']
        if 'action' in data:
            permission.action = data['action']
        
        db.session.commit()
        
        return jsonify({
            'code': 200,
            'message': '更新成功',
            'data': {
                'id': permission.id,
                'name': permission.name,
                'resource_id': permission.resource_id,
                'action': permission.action
            }
        })
    except Exception as e:
        db.session.rollback()
        return jsonify({'code': 500, 'message': f'更新失败: {str(e)}'}), 500

@views_bp.route('/permissions/<int:permission_id>', methods=['DELETE'])
def delete_permission(permission_id):
    """删除权限"""
    try:
        permission = Permission.query.get(permission_id)
        if not permission:
            return jsonify({'code': 404, 'message': '权限不存在'}), 404
        
        db.session.delete(permission)
        db.session.commit()
        
        return jsonify({'code': 200, 'message': '删除成功'})
    except Exception as e:
        db.session.rollback()
        return jsonify({'code': 500, 'message': f'删除失败: {str(e)}'}), 500
